import 'dart:collection';
import 'dart:convert';

import 'package:flustars/flustars.dart';

class Dictionaries {
  String label;
  String value;

  Dictionaries.fromParams({this.value, this.label});

  Dictionaries.fromJson(jsonRes) {
    label = jsonRes['label'];
    value = jsonRes['value'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['label'] = this.label;
    data['value'] = this.value;
    return data;
  }
}

class DictionariesMap extends SplayTreeMap<String, List<Dictionaries>> {
  DictionariesMap.fromJson(jsonRes) {
    Map map = jsonRes;
    map.forEach((key, value) {
      SpUtil.putString(key, jsonEncode(value));
    });
  }

  ///flutter解析json数组
  ///https://blog.csdn.net/philosowhy/article/details/84592040
  static List<Dictionaries> getDicByKey(String key) {
    String keyDic = SpUtil.getString(key);
    if (TextUtil.isEmpty(keyDic)) return null;
    List responseJson = json.decode(keyDic);
    List<Dictionaries> dicList =
        responseJson.map((e) => new Dictionaries.fromJson(e)).toList();

    return dicList;
  }

  /// 通过字典中的值获取label
  /// dicType 字典类型
  /// value 字典值
  static String getLabelByValue(String dicType, String value) {
    if (TextUtil.isEmpty(value)) return '';
    List<Dictionaries> dictionaries = getDicByKey(dicType);
    dictionaries.forEach((e) {
      if (value == e.value) return e.label;
    });
    return value;
  }
}
